package com.sright.bcard.content.biz.manager.impl;

import com.sright.bcard.common.service.share.dto.LoginUser;
import com.sright.bcard.content.biz.manager.UserTagManager;
import com.sright.bcard.content.dal.dao.UserTagsDAO;
import com.sright.bcard.content.dal.entity.UserTagsDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author peter
 * @description
 * @date 2020/6/4
 */
@Service
public class UserTagManagerImpl implements UserTagManager {

    @Autowired
    private UserTagsDAO userTagsDAO;

    @Override
    public Boolean removeUserTag(Long tagId) {
        return userTagsDAO.deleteByTagId(tagId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean addUserTag(Long userId, String tags, LoginUser loginUser) {
        if (userId == null) {
            return false;
        }
        Long enterpriseId = loginUser.getEnterpriseId();
        if (enterpriseId == null) {
            return false;
        }

        if (tags == null || tags.isEmpty()) {
            userTagsDAO.deleteByUserId(userId);
            return false;
        }

        List<UserTagsDO> userTagsDOList = userTagsDAO.selectByEnterpriseIdAndUserId(enterpriseId, userId);

        List<Long> oldTags = userTagsDOList.stream().map(UserTagsDO::getTagId).collect(Collectors.toList());
        List<Long> newTags =
                Arrays.asList(tags.split(",")).stream().map(x -> Long.valueOf(x)).collect(Collectors.toList());

        List<UserTagsDO> removeList =
                userTagsDOList.stream().filter(m -> !newTags.contains(m.getTagId())).collect(Collectors.toList());
        List<Long> addList = newTags.stream().filter(m -> !oldTags.contains(m)).collect(Collectors.toList());

        removeList.forEach(tagsDO -> userTagsDAO.deleteByPrimaryKey(tagsDO.getId()));
        addList.forEach(tagId -> {
            UserTagsDO userTagsDO = new UserTagsDO();
            userTagsDO.setEnterpriseId(Long.parseLong(enterpriseId.toString()));
            userTagsDO.setAnalysisId(Long.parseLong(userId.toString()));
            userTagsDO.setTagId(tagId);
            userTagsDO.setCreatedAt(new Date());
            userTagsDO.setUpdatedAt(new Date());
            userTagsDAO.insert(userTagsDO);
        });

        return true;
    }
}
